# -*- coding:utf-8 -*-
import threading
from time import sleep

from adb_core import AdbCore


class AdbLogcat:
    def __init__(self):
        self.adb = AdbCore()

        self.filter = ""
        self.logcat_loop_id = 0
        self.recv_cache = []

    def set_filter(self, filter_str):
        self.filter = filter_str

    def get_start_cmd(self):
        command = "shell:logcat %s" % self.filter
        return command

    def start(self, logcat_callback):
        self.logcat_loop_id += 1
        print "logcat start, filter: %s" % self.filter
        if not self.adb.connect():
            print "no connection"
            return 0
        self.adb.write(self.get_start_cmd())
        if self.adb.status(self.adb.read(raw=True)):
            # thread.start_new_thread(self.thread_read, (self.adb.read, logcat_callback))
            t1 = threading.Thread(target=self.thread_read, args=(self.adb.read, logcat_callback))
            t1.setDaemon(False)
            t1.start()

    def thread_read(self, read, logcat_callback):
        try:
            loop_id = self.logcat_loop_id
            while loop_id == self.logcat_loop_id:
                sleep(0.1)
                return_data = read(raw=True)
                print "new recv ---------->"
                print return_data
                if len(self.recv_cache):
                    return_data = self.recv_cache.pop(0) + return_data
                logcat_lines = return_data.split("\r\n")
                if len(logcat_lines[-1]) > 0:
                    self.recv_cache.append(logcat_lines.pop())
                else:
                    logcat_lines.pop()  # 移出空行
                for logcat_line in logcat_lines:
                    # logcat_line = self.formatter.logcat_format(logcat_line)
                    if len(logcat_line):
                        print logcat_line
                        logcat_callback(logcat_line)
        except Exception as e:
            print "thread_read error:", e
        # except KeyboardInterrupt:
        #     print "exit"

    def stop(self):
        self.logcat_loop_id += 1

    def log_split(self, log_stream):
        return ["line1", "line2", ]

if __name__ == "__main__":
    def print_log(log_str):
        print log_str
    a = AdbLogcat()
    a.adb.set_sn("0815f84901a31004")
    a.set_filter("| grep -E 'StatLogger.*logtype'")
    print "start..."
    a.start(print_log)